<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang
// +----------------------------------------------------------------------

/**
 * 后台用户类
 * @package  htdocs
 * @author   allen.qiang
 * @version 1.0
 */

class sysUser {

    private $dbca;

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }

    /**
     * 查询用户信息
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchUserInfo( &$arg_array ) {
        global $G_SHOP;
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //用户名
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= ' AND userID LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['userID']) . '%';
        }

        //手机号
        if (isset($arg_array['mobile']) && !empty($arg_array['mobile'])) {
            $sql .= ' AND mobile = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['mobile'];
        }

        //使用状态
        if (isset($arg_array['useFlg']) && in_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        //用户姓名
        if (isset($arg_array['trueName']) && !empty($arg_array['trueName'])) {
            $sql .= ' AND trueName LIKE ?';
            $params_type .= 's';
            $params_array[] = '%' . trim($arg_array['trueName']) . '%';
        }

        //部门ID
        if (isset($arg_array['departmentID']) && is_numeric($arg_array['departmentID']) ) {
            $sql .= ' AND departmentID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['departmentID'];
        }

        //部门ID
        if (isset($arg_array['isSalesman']) && is_numeric($arg_array['isSalesman']) ) {
            $sql .= ' AND isSalesman = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['isSalesman'];
        }

        //城市ID
        if (isset($arg_array['cityID']) && is_numeric($arg_array['cityID']) ) {
            $sql .= ' AND cityID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['cityID'];
        }

        //绑定wx_openid
        if (isset($arg_array['wx_openid']) && $arg_array['wx_openid']!="") {
            $sql .= ' AND wx_openid = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['wx_openid'];
        }

        //拓展字段
        if (isset($arg_array['extend']) && !empty($arg_array['extend'])) {

            $login_session =  $G_SHOP->sessionCache_get ( 'PS_LOGIN_SESSION' );
            $str_departmentID= strstr($arg_array['extend'],"(");
            $str_departmentID=str_replace('(',',',$str_departmentID) ;
            $str_departmentID=str_replace(')',',',$str_departmentID) ;

            if(strpos($str_departmentID,",".$login_session['department'].",")>-1){
                $str_departmentID=str_replace(','.$login_session['department'].',',',',$str_departmentID) ;
                $str_departmentID=trim($str_departmentID,',');
                if($str_departmentID==""){
                    $sql.=" AND (departmentID=".$login_session['department']." AND userID='".$G_SHOP->currentUserID."')";
                }else{
                    $sql.=" AND (departmentID IN ( ".$str_departmentID." ) OR departmentID=".$login_session['department']." AND userID='".$G_SHOP->currentUserID."')";
                }
            }else{
                $sql .= $arg_array['extend'];
            }
        }

        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_master ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }else{

                    $arg_array['count'] = $item_count;
                    //分页bug处理
                    if ($arg_array['count'] < $arg_array['rp']) {

                        $arg_array['page'] = 1;
                    }
                    //排序
                    if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                        $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                    //分页
                    if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                        $arg_array['page'] = 1;

                    $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);
                }
            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_master ' . $sql;

            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array) {
                return null;
            }

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'userID' => $item->userID,
                    'trueName' => $item->trueName,
                    'userPwd' => $item->userPwd,
                    'email' => $item->email,
                    'useFlg' => $item->useFlg,
                    'deliveryID' => $item->deliveryID,
                    'mobile' => $item->mobile,
                    'phone' => $item->phone,
                    'isSalesman' => $item->isSalesman,
                    'cityID' => $item->cityID,
                    'cityName' => $item->cityName,
                    'distributionID' => $item->distributionID,
                    'distributionName' => $item->distributionName,
                    'departmentID' => $item->departmentID,
                    'departmentName' => $item->departmentName,
                    'wx_openid' => $item->wx_openid,
                    'extend_1' => $item->extend_1,
                    'extend_2' => $item->extend_2,
                    'extend_3' => $item->extend_3,
                    'extend_4' => $item->extend_4,
                    'extend_5' => $item->extend_5,
                    'extend_6' => $item->extend_6,
                    'extend_7' => $item->extend_7,
                    'extend_8' => $item->extend_8
                );

            }
            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    public function getUserInfo( &$arg_array ) {
        global $G_SHOP;
        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //用户名
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= ' userID = ?';
            $params_type .= 's';
            $params_array[] =  trim($arg_array['userID']);
        }

        //查询分类信息
        $search_sql = 'SELECT * FROM user_master WHERE ' . $sql;

        $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
        if (!$temp_item_array) {
            return null;
        }

        foreach($temp_item_array as &$item) {

            $item_array[] = array(
                'uuid' => $item->uuid,
                'userID' => $item->userID,
                'trueName' => $item->trueName,
                'userPwd' => $item->userPwd,
                'email' => $item->email,
                'useFlg' => $item->useFlg,
                'deliveryID' => $item->deliveryID,
                'mobile' => $item->mobile,
                'phone' => $item->phone,
                'isSalesman' => $item->isSalesman,
                'cityID' => $item->cityID,
                'cityName' => $item->cityName,
                'distributionID' => $item->distributionID,
                'distributionName' => $item->distributionName,
                'departmentID' => $item->departmentID,
                'departmentName' => $item->departmentName,
                'extend_1' => $item->extend_1,
                'extend_2' => $item->extend_2,
                'extend_3' => $item->extend_3,
                'extend_4' => $item->extend_4,
                'extend_5' => $item->extend_5,
                'extend_6' => $item->extend_6,
                'extend_7' => $item->extend_7,
                'extend_8' => $item->extend_8
            );

        }
        return $item_array;


    }




    /**
     * 新增或修改用户信息
     * @param array $arg_array 用户数组
     * @return array
     */
    public function editUser ( $arg_array ) {

        //加载角色类
        quanli_require('module/base/system/sysRole.class.php');

        //实例化公共类
        $sysRole = new sysRole( $this->dbca );

        if (!isset($arg_array['operator'], $arg_array['userID'], $arg_array['pop_trueName'], $arg_array['userPwd'], $arg_array['repeatPwd'],
            $arg_array['email'],$arg_array['mobile'], $arg_array['uuid']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (empty($arg_array['userID'])) {
            return array( 'code' => 400, 'message' => '用户名不能为空' );
        }

        if (empty($arg_array['pop_trueName'])) {
            return array( 'code' => 400, 'message' => '用户姓名不能为空' );
        }

       if (empty($arg_array['mobile'])) {
           return array('code' => 400, 'message' => '手机号码不能为空');
       }

        if (empty($arg_array['uuid']) || (!empty($arg_array['uuid']) && !empty($arg_array['userPwd']))) {

            if (!is_pwd($arg_array['userPwd'])) {
                return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号的组合' );
            }
            if ($arg_array['userPwd'] != $arg_array['repeatPwd']) {
                return array( 'code' => 400, 'message' => '两次输入的密码不一致' );
            }

        }

        if (!empty($arg_array['mobile']) && !is_mobile($arg_array['mobile'])) {
            return array( 'code' => 400, 'message' => '手机号码格式错误' );
        }

        if (!empty($arg_array['email']) && !is_email($arg_array['email'])) {
            return array( 'code' => 400, 'message' => '邮件格式错误' );
        }

        if (empty($arg_array['user_role'])) {
            return array( 'code' => 400, 'message' => '请选择用户角色' );
        }


        if (!isset($arg_array['useFlg']) || !in_array($arg_array['useFlg'], array(0, 1))) {
            $arg_array['useFlg'] = 1;
        }

        try {

            $this->dbca->beginTransaction();

            //检查并保存用户信息
            $user_obj = new entity('user_master');
            $user_obj->userID = $arg_array['userID'];
            if ($this->dbca->fetch($user_obj)) {

                if ($user_obj->uuid != $arg_array['uuid']) {
                    throw new Exception('用户已存在，请使用其他用户名', 404);
                }

            } else {

                if (!empty($arg_array['uuid'])) {
                    throw new Exception('用户信息没有找到', 404);
                }
                $user_obj->creator = $arg_array['operator'];

            }
            $user_obj->trueName = $arg_array['trueName'];
            if (!empty($arg_array['userPwd']))
                $user_obj->userPwd = md5($arg_array['userPwd']);
            $user_obj->trueName = $arg_array['pop_trueName'];
            $user_obj->email = $arg_array['email'];
            $user_obj->mobile = $arg_array['mobile'];
            $user_obj->isSalesman = $arg_array['isSalesman'];
            $user_obj->extend_1 = null;
            $user_obj->extend_3 = null;
            $user_obj->useFlg = $arg_array['useFlg'];
            $user_obj->cityID = $arg_array['cityID'];
            $user_obj->cityName = $arg_array['cityName'];
            $user_obj->distributionID = $arg_array['distributionID'];
            $user_obj->distributionName = $arg_array['distributionName'];
            $user_obj->departmentID = isset($arg_array['departmentID']) ? $arg_array['departmentID'] : "" ;
            $user_obj->departmentName = isset($arg_array['departmentName']) ? $arg_array['departmentName'] : "";
            $this->dbca->save( $user_obj );

            //删除用户角色信息
            $del_sql = 'DELETE FROM user_userrole WHERE userID = ?';
            $this->dbca->stmt_query($del_sql, 's', $arg_array['userID']);

            //保存用户的角色信息
            $role_num = 0;

            foreach($arg_array['user_role'] as &$role_id) {

                //查询角色信息
                $r_arg_array = array(
                    'roleID' => $role_id
                );
                $role_array = $sysRole->searchRole( $r_arg_array );
                if (!$role_array) {
                    continue;
                }

                $role_obj = new entity('user_userrole');
                $role_obj->creator = $arg_array['operator'];
                $role_obj->userID = $arg_array['userID'];
                $role_obj->roleID = $role_id;
                if ($this->dbca->save($role_obj)) {
                    ++$role_num;
                }

            }

            if ($role_num == 0) {
                throw new Exception('用户角色保存失败', 404);
            }

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => '用户信息保存成功' );

    }

    /**
     * 查询用户的角色信息
     * @param string $userID 用户名
     * @return null
     */
    public function searchUserRole( $userID ) {

        if (!isset($userID) || empty($userID)) {
            return null;
        }

        $search_sql = 'SELECT * FROM user_userrole WHERE userID = ?';
        $user_role_array = &$this->dbca->stmt_query($search_sql, 's', $userID);
        if (!$user_role_array) {
            return null;
        }

        foreach($user_role_array as &$role) {
            $item_array[$role->roleID] = $role->roleID;
        }

        return $item_array;

    }

    /**
     * 启用或禁用用户
     * @param array $arg_array
     * @return array
     */
    public function changeUserUse ( $arg_array ) {

        if (!isset($arg_array['userID'], $arg_array['useFlg']) || empty($arg_array['userID']) || !in_array($arg_array['useFlg'], array(0, 1))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            //查询用户信息
            $user_obj = new entity('user_master');
            $user_obj->userID = $arg_array['userID'];
            if (!$this->dbca->fetch($user_obj)) {
                throw new Exception('用户信息没有找到', 404);
            }

            if ($user_obj->useFlg == 1 && $arg_array['useFlg'] == 1) {
                throw new Exception('用户已启用', 404);
            }

            if ($user_obj->useFlg == 0 && $arg_array['useFlg'] == 0) {
                throw new Exception('用户已禁用', 404);
            }
            $user_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save($user_obj);

            if ($arg_array['useFlg'] == 1) {
                return array( 'code' => 200, 'message' => '用户启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '用户禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 批量删除用户
     * @param array $user_array 用户数组
     * @return array
     */
    public function deleteUser( $user_array ) {

        if (!isset($user_array) || !is_array($user_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            if (!empty($user_array)) {

                foreach($user_array as &$userID) {

                    //查询用户信息
                    $user_obj = new entity('user_master');
                    $user_obj->userID = $userID;
                    if (!$this->dbca->fetch($user_obj)) {
                        continue;
                    }
                    $this->dbca->delete($user_obj);

                }

            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => '用户删除成功' );

    }

    //绑定微信openId
    public function bindOpenId ( $id, $openId )
    {
        global $G_SHOP;
        //查询配送员
        $user = new entity('user_master');
        $user->uuid = $id;
        if (!$G_SHOP->DBCA->fetch($user))
            return array( 'code' => 404, 'message' => '销售员信息没有找到' );

        $user->wx_openid = $openId;
        $G_SHOP->DBCA->save($user);
        return array( 'code' => 200, 'message' => '' );
    }

}
